/* 
OLDC_Object Class
Holding infos about an object related to how it has been transformed
*/
// Global Variables
var templateId;
var svgCanvas = new OLDC_SvgCanvas();
var prevMouseMoveEventTime = 0;
var prevClientX = 0;
var prevClientY = 0;
var mouseSpeedX = 0;
var mouseSpeedY = 0;
var distX = 0;
var distY = 0;
var elapsedTime = 0;
var clickedObjectID = '';
var movingCanvas = false;
var maxZoomRatio = 2;
var unFocusedObjectOpacity = 0.5;
var noteMaximumLength = 95;
var iconizedObjectHeight = 48;
//var iconizedObjectWidth = 8;
var currentIconX = 0;
var currentIconY = 0;
var iconSpacing = 30;
var distanceMeasurement = false;
var lineType;
var actionHistory = require("oldc_history");
var utils = require("utils");
var api = require("service");
var icons;
var parameters;
// When document is ready
$(function() {
	var svg = null;
	templateId = utils.getUrlParam("id");
	if (!templateId) {
		alert("system error!");
	}
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		height: 600,
		width: 600,
		modal: true
	});
	var paraPromise = api.getParameters(templateId);
	var iconPromise = api.getIcons();
	Promise.all([paraPromise, iconPromise]).then(function (values) {
		parameters = values[0];
		icons = values[1];
		$("#svgcontainer").svg({onLoad: initSVG});
	}).catch(function(error){
		console.error(error.message);
		alert("systemError:"+error.message);
	})

	document.ontouchmove = function(evt) { evt.preventDefault(); }
	$("#undo_button").click(function (event) {
		actionHistory.revocation();
	});
	$("#save_button").click(function (event) {
		if (svgCanvas.list ) {
			var parameters = [];
			for (var obj in svgCanvas.list) {
				var OLDC_Obj = svgCanvas.list[obj];
				if (OLDC_Obj.isAClone) {
					if (OLDC_Obj.iconName == 'line' || OLDC_Obj.iconName == 'arrow') {
						if (!OLDC_Obj.left_x || !OLDC_Obj.left_y || !OLDC_Obj.right_x || !OLDC_Obj.right_y) {
							continue;
						}
					}
					var parammeterJson = {iconId:OLDC_Obj.iconId,svgInfo:JSON.stringify(new Parameter(OLDC_Obj))};
					if (OLDC_Obj.parameterId) {
						parammeterJson.id=OLDC_Obj.parameterId;
					}
					parameters.push(parammeterJson);
				}
			}
			api.saveParameters(templateId, JSON.stringify(parameters)).then(function(result){
				alert("save success!");
			}).catch(function(error){
				alert("save error:"+error.message);
				console.log("异常:");
				console.log(error);
			})
			// $.ajax(utils.baseUrl+'parameter/save',{'method':'Post','data':JSON.stringify(parameters)}).then(function(result){
			// 	alert(result);
			// }).failed
			
		}
	});
	$("#info_button").click(function (event) {
		mousedblclick_listener(event);
	});
    $(document).mousedown(mousedown_listener);
	$(".line").click(function(event){
		var type = event.target.id;
		if (event.target.checked) {
			if (type == 'line') {
				$("#arrow").attr("checked", false);
			}else{
				$("#line").attr("checked", false);
			}
			lineType = type;
			distanceMeasurement = true;
		}else{
			lineType = null;
			distanceMeasurement = false;
		};
	});
	
	function loadGrid() {
		svg.load('./svg/grid.svg', {addTo: true, onLoad: svgCanvas.loadObjectList});
	}
		
	function initContainer() {
		svg.load('./svg/defs.svg', {addTo: true, onLoad: loadGrid});
	}
	
	function initSVG(){
		svg = $("#svgcontainer").svg('get');
		svgCanvas.setSVGCanvas(svg);
		initContainer();
	}	


	$("#size_slider").slider({
		min: 0.25, max: 2.5, step:0.02, value: 1, disabled: true, 
		slide: function(event, ui) {
			actionHistory.clear();
			actionHistory.push(svgCanvas.list[ svgCanvas.selectedObjectID ],'size');
			var sliderValue = $("#size_slider").slider("value");
			$("#size_title").html("Size: " + sliderValue);
 	        svgCanvas.list[ svgCanvas.selectedObjectID ].zoomRatio = sliderValue;
			svgCanvas.transform( svgCanvas.selectedObjectID);
		}
	});

	$("#angle_slider").slider({
		min: -181, max: 181, step:1, value: 1, disabled: true,
		slide: function(event, ui) {
			actionHistory.clear();
			actionHistory.push(svgCanvas.list[svgCanvas.selectedObjectID ],'angle');
			var sliderValue = $("#angle_slider").slider("value");
			$("#angle_title").html("Angle: " + sliderValue);
 	        svgCanvas.list[ svgCanvas.selectedObjectID ].angle = sliderValue;
			svgCanvas.transform( svgCanvas.selectedObjectID );
		}
	});

	$("#bringToFront").click(function() {
		svgCanvas.bringToFront( svgCanvas.selectedObjectID );
	});

	$("#bringToBack").click(function() {
		svgCanvas.bringToBack( svgCanvas.selectedObjectID );
	});

	$("#removeObject").click(function() {
		svgCanvas.removeObject( svgCanvas.selectedObjectID );
	});
	
	$("#removeAllObject").click(function() {
		svgCanvas.removeObject( "all" );
	});
	
	$("#unselectObject").click(function() {
		svgCanvas.clearSelection();
		svgCanvas.toggleFocus();
	});

	$("#note").attr( 'maxlength', noteMaximumLength );
	$().maxlength();
	
	$("#addnote").click(function() {
		var soid = svgCanvas.selectedObjectID;
		if (!soid) {
			alert("please select one object!");
			return false;
		}
		var obj  = svgCanvas.list[svgCanvas.selectedObjectID]
		var s = $("#note").val();
				
		text = utils.wordwrap( s, 19, '' );
		
		var g = svgCanvas.svg.group();
		var frame = svgCanvas.svg.rect( g, obj.currentX, obj.currentY+50, 124, 56,
									  {fill: '#FFFD80', stroke:'darkgrey', strokeWidth:1} );
		if (!hasArrowDef) {
			hasArrowDef = true;
			var defs = svgCanvas.svg.defs('arrowDef');
			var marker = svgCanvas.svg.marker(defs, 'arrowMarker', 5, 5, 10, 10,'auto-start-reverse',{stroke:"#020102", fill:"#020102"});
			var arrowPath = svgCanvas.svg.createPath();
			svgCanvas.svg.path(marker, arrowPath.move(0, 0).line(10,5).line(0,10).close());
		}
		var path = svgCanvas.svg.createPath();
		svgCanvas.svg.path(g, path.move( obj.currentX, obj.currentY+50).line( obj.currentX, obj.currentY),
				{fill: 'none', stroke: '#020102', strokeWidth: 2,"marker-end":"url(#arrowMarker)"});



		for( var i in text ) {
			var note = svg.text(g, obj.currentX+4, (obj.currentY+50+12 + ( i*10 ) ), text[i],
								{fontFamily: 'Courier New', fontSize: '10', fill: 
								'black'});
		}
		var noteObjectID = svgCanvas.addObject( g );
		
		svgCanvas.list[noteObjectID].isAClone = true;
	});

	$("#generate_diagram_button").click(function() {
		svgCanvas.clearSelection();
		svgCanvas.toggleFocus();
		var svgData = svgCanvas.generateSVG();
		$("#result").val( svgData );
	});

	$("#objectlist_selection").change(function(evt){
		$("select option:selected").each(function () {
			svgCanvas.loadObjectListByOption(  $(this).val() );
          });
	});
	$(".paginItem a").click(function(evt){
		var obj = $("#objectlist_selection").val();
		svgCanvas.loadPage( obj,this.innerText);

	});
	
	$(".controls_slider").slider( "option", "disabled", true );
	$(".object_control_button").attr("disabled", "disabled");

    $(document).mousedown(mousedown_listener);

});
